package com.stormrage.edu.ctrl.ent;

import java.util.List;

import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import com.alibaba.fastjson.JSON;
import com.stormrage.edu.serv.adm.AdmAcctServ;
import com.stormrage.edu.serv.ent.EntAcctServ;
import com.stormrage.edu.serv.ent.EntEnterpriseScoreServ;
import com.stormrage.edu.serv.ent.EntEnterpriseServ;
import com.stormrage.entity.adm.AdmRes;
import com.stormrage.entity.ent.EntEnterprise;
import com.stormrage.entity.ent.rep.EntAcctRep;
import com.stormrage.entity.ent.req.EntAcctReq;
import com.stormrage.entity.ent.req.EntEnterpriseReq;
import com.stormrage.entity.rep.ErrorRep;
import com.stormrage.entity.rep.JsonRep;
import com.stormrage.entity.rep.ListRep;
import com.stormrage.entity.shiro.ShiroAcct;
import com.stormrage.shiro.bind.CurrentUser;
import com.stormragetech.core.ctrl.BaseCtrl;
import com.stormragetech.core.entity.Page;

@Controller
@RequestMapping("/ent")
public class EntCtrl extends BaseCtrl {

	private static final Logger logger = LoggerFactory.getLogger(EntCtrl.class);

	@Value("#{constants['html.title']}")
	private String htmlTitle;

	@Value("#{constants['url.root']}")
	private String rootUrl;

	@Value("#{constants['path.excel']}")
	private String excelPath;

	@Autowired
	private AdmAcctServ admAcctServ;

	@Autowired
	private EntAcctServ entAcctServ;

	@Autowired
	private EntEnterpriseServ entEnterpriseServ;

	@Autowired
	private EntEnterpriseScoreServ entEnterpriseScoreServ;

	@RequiresPermissions("ent:create")
	@RequestMapping(value = "/create", method = RequestMethod.GET)
	public String create(@CurrentUser ShiroAcct curr, Model model) {

		logger.debug(" 【 Controller 】- 【 EntCtrl 】- 【 Registration 】-【 GET/POST 】-【 STARTED 】");

		try {

			// ------------------ 获取用户操作的 Menu ------------------
			List<AdmRes> menus = admAcctServ.queryMenuById(Integer.valueOf(curr.getId()));

			// ------------------ 获取菜单 ------------------

			model.addAttribute("user", curr);
			model.addAttribute("menus", menus);
			model.addAttribute("htmlTitle", htmlTitle);
			model.addAttribute("path", rootUrl + excelPath);

		} catch (Exception e) {
			model.addAttribute("err", e.getMessage());
			return "error/500";
		}

		logger.debug(" 【 Controller 】-【 EntCtrl 】-【 Create 】-【 GET 】-【 COMPLETED 】");
		return "ent/ent/create";

	}

	@RequiresPermissions("ent:create")
	@RequestMapping(value = "/create", method = RequestMethod.POST)
	public String create(@CurrentUser ShiroAcct curr,
			@RequestParam(value = "file", required = false) MultipartFile file,
			@RequestParam(value = "enterprise", required = false) String enterprise, RedirectAttributes redirect) {

		logger.debug(" 【 Controller 】-【 EntCtrl 】-【 Create 】-【 POST 】-【 STARTED 】");

		ErrorRep err = null;
		String errMsg = "";

		try {

			// ------------------ Ctrl操作 ------------------
			if (!file.isEmpty()) { // 上传文件方式
				entEnterpriseServ.upload(file);
			} else { // 直接添加方式
				EntEnterprise entity = EntEnterprise.instance(enterprise);
				entEnterpriseServ.create(entity);
			}

			errMsg = "提示信息：添加公司成功";
			err = ErrorRep.instance(true, errMsg);
			redirect.addFlashAttribute("err", err);

		} catch (Exception e) {
			errMsg = "提示信息：添加公司失败";
			err = ErrorRep.instance(false, errMsg);
			redirect.addFlashAttribute("err", err);
			return "redirect:/ent/list";
		}

		logger.debug(" 【 Controller 】-【 EntCtrl 】-【 Create 】-【 POST 】-【 COMPLETED 】");
		return "redirect:/ent/list";

	}

	@RequiresPermissions("chap:view")
	@RequestMapping(value = "/list")
	public String list(@CurrentUser ShiroAcct curr, EntEnterpriseReq req, Model model) {

		logger.debug(" 【 Controller 】-【 EntCtrl 】-【 List 】-【 POST 】-【 STARTED 】");

		try {

			// ------------------ 获取用户操作的 Menu ------------------
			List<AdmRes> menus = admAcctServ.queryMenuById(Integer.valueOf(curr.getId()));

			// ------------------ Ctrl操作 ------------------
			String search = JSON.toJSONString(req);

			logger.debug(" 查询条件req变为search为 " + search);

			if (null != search && search.length() > 0)
				model.addAttribute("search", search);

			model.addAttribute("user", curr);
			model.addAttribute("menus", menus);
			model.addAttribute("htmlTitle", htmlTitle);

			model.addAttribute("form", req);

		} catch (Exception e) {
			model.addAttribute("err", e.getMessage());
			return "error/500";
		}

		logger.debug(" 【 Controller 】-【 EntCtrl 】-【 List 】-【 GET 】-【 COMPLETED 】");
		return "ent/ent/list";
	}

	@RequiresPermissions("chap:view")
	@RequestMapping(value = "/ajax", method = RequestMethod.POST, produces = "text/html;charset=UTF-8")
	@ResponseBody
	public String ajax(@RequestParam(value = "draw", required = true) Integer draw,
			@RequestParam(value = "start", required = true) Integer start,
			@RequestParam(value = "length", required = true) Integer length, EntEnterpriseReq req) {

		logger.debug(" 【 Controller 】- 【 EntCtrl 】- 【 Ajax 】-【 POST 】-【 STARTED 】");

		String json = null;

		try {

			// ------------------ 获取初始化模块的状态 ------------------
			Page page = Page.instance(start, length, 1);
			req.setPage(page);
			draw += 1;

			logger.debug(" 分页信息为 " + page.toString());

			ListRep entity = entEnterpriseServ.queryList(req);

			JsonRep rep = JsonRep.instance(entity.getCount(), draw, entity.getList());
			json = JSON.toJSONString(rep);

		} catch (Exception e) {
			return "error/500";
		}

		logger.debug(" 返回的json为 " + json);
		logger.debug(" 【 Controller 】- 【 EntCtrl 】- 【 Ajax 】-【 POST 】-【 COMPLETED 】");
		return json;

	}

	@RequiresPermissions("ent:view")
	@RequestMapping(value = "/list/{id}")
	public String list(@CurrentUser ShiroAcct curr, @PathVariable("id") Integer id, Model model) {

		logger.debug(" 【 Controller 】-【 EntCtrl 】-【 List 】-【 POST 】-【 STARTED 】");

		try {

			// ------------------ 获取用户操作的 Menu ------------------
			List<AdmRes> menus = admAcctServ.queryMenuById(Integer.valueOf(curr.getId()));

			// ------------------ Ctrl操作 ------------------
			EntAcctReq req = EntAcctReq.instance(id, 0);
			List<EntAcctRep> array = entAcctServ.queryListByEntIdLock(req);

			model.addAttribute("user", curr);
			model.addAttribute("menus", menus);
			model.addAttribute("htmlTitle", htmlTitle);

			model.addAttribute("data", array);

		} catch (Exception e) {
			model.addAttribute("err", e.getMessage());
			return "error/500";
		}

		logger.debug(" 【 Controller 】-【 EntCtrl 】-【 List 】-【 GET 】-【 COMPLETED 】");
		return "ent/acct/list";
	}

	@RequiresPermissions("ent:edit")
	@RequestMapping(value = "/pass")
	public String pass(@CurrentUser ShiroAcct curr, Model model) {

		logger.debug(" 【 Controller 】-【 EntCtrl 】-【 PASS 】-【 GET | POST 】-【 STARTED 】");

		try {

			// ------------------ 获取用户操作的 Menu ------------------
			List<AdmRes> menus = admAcctServ.queryMenuById(Integer.valueOf(curr.getId()));

			// ------------------ Ctrl操作 ------------------
			List<EntAcctRep> array = entAcctServ.queryListForPass();

			model.addAttribute("user", curr);
			model.addAttribute("menus", menus);
			model.addAttribute("htmlTitle", htmlTitle);

			model.addAttribute("data", array);

		} catch (Exception e) {
			model.addAttribute("err", e.getMessage());
			return "error/500";
		}

		logger.debug(" 【 Controller 】-【 EntCtrl 】-【 List 】-【 GET | POST 】-【 COMPLETED 】");
		return "ent/acct/pass";
	}

	@RequiresPermissions("ent:edit")
	@RequestMapping(value = "/pass/{cid}/{id}")
	public String pass(@CurrentUser ShiroAcct curr, @PathVariable("id") Integer id, RedirectAttributes redirect) {

		logger.debug(" 【 Controller 】-【 EntCtrl 】-【 PASS 】-【 GET | POST 】-【 STARTED 】");

		ErrorRep err = null;
		String errMsg = "";

		try {

			// ------------------ Ctrl操作 ------------------
			entAcctServ.updateLock(id);
			errMsg = "提示信息：通过企业管理员审核成功";
			err = ErrorRep.instance(true, errMsg);
			redirect.addFlashAttribute("err", err);

		} catch (Exception e) {
			errMsg = "提示信息：通过企业管理员审核失败";
			err = ErrorRep.instance(false, errMsg);
			redirect.addFlashAttribute("err", err);
			return "redirect:/ent/pass/{cid}/{id}";
		}

		logger.debug(" 【 Controller 】-【 EntCtrl 】-【 List 】-【 GET | POST 】-【 COMPLETED 】");
		return "redirect:/ent/list/{cid}";
	}

	@RequiresPermissions("ent:edit")
	@RequestMapping(value = "/lock/{id}")
	public String lock(@CurrentUser ShiroAcct curr, @PathVariable("id") Integer id, RedirectAttributes redirect) {

		logger.debug(" 【 Controller 】-【 EntCtrl 】-【 lock 】-【 GET | POST 】-【 STARTED 】");

		ErrorRep err = null;
		String errMsg = "";

		try {

			// ------------------ Ctrl操作 ------------------
			entEnterpriseScoreServ.update(id);
			errMsg = "提示信息：更改企业上传成绩权限成功";
			err = ErrorRep.instance(true, errMsg);
			redirect.addFlashAttribute("err", err);

		} catch (Exception e) {
			errMsg = "提示信息：更改企业上传成绩权限失败";
			err = ErrorRep.instance(false, errMsg);
			redirect.addFlashAttribute("err", err);
			return "redirect:/ent/list";
		}

		logger.debug(" 【 Controller 】-【 EntCtrl 】-【 lock 】-【 GET | POST 】-【 COMPLETED 】");
		return "redirect:/ent/list";

	}

	@RequiresPermissions("ent:edit")
	@RequestMapping(value = "/init/{cid}/{id}")
	public String init(@CurrentUser ShiroAcct curr, @PathVariable("id") Integer id, RedirectAttributes redirect) {

		logger.debug(" 【 Controller 】-【 EntCtrl 】-【 PASS 】-【 GET | POST 】-【 STARTED 】");

		ErrorRep err = null;
		String errMsg = "";

		try {

			// ------------------ Ctrl操作 ------------------
			entAcctServ.updatePass(id);
			errMsg = "提示信息：初始化企业管理员密码成功";
			err = ErrorRep.instance(true, errMsg);
			redirect.addFlashAttribute("err", err);

		} catch (Exception e) {
			errMsg = "提示信息：初始化企业管理员密码失败";
			err = ErrorRep.instance(false, errMsg);
			redirect.addFlashAttribute("err", err);
			return "redirect:/ent/list/{cid}";
		}

		logger.debug(" 【 Controller 】-【 EntCtrl 】-【 List 】-【 GET | POST 】-【 COMPLETED 】");
		return "redirect:/ent/list/{cid}";

	}

}
